﻿using System;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Input;
using System.Collections;
using System.Text;

namespace MichMan.Utilities
{
    public static class GuidUtility
    {
        /// <summary>
        /// C# implementation of http://msdn.microsoft.com/en-us/library/aa380052%28VS.85%29.aspx
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        private static readonly string charMap = "abcdefghijklmnopqrstuvwxyz012345";

        public static string GuidToStorageName(Guid guid)
        {
            StringBuilder builder = new StringBuilder();
            BitArray bits = new BitArray(guid.ToByteArray());
            bits.Length = 130;
            var bitList = bits.OfType<bool>().ToList();
            for (int i = 0; i < bits.Length / 5; i++)
            {
                BitArray index = new BitArray(bitList.Skip(i * 5).Take(5).ToArray());
                index.Length = 8;
                var theBits = index.OfType<bool>().Reverse();
                byte theByte = 0;
                int j = 0;
                foreach (var bit in theBits)
                {
                    theByte += bit ? (byte)(2 ^ ++j) : (byte)0;
                }

                char newChar = charMap[theByte];
                if (i % 8 == 0)
                {
                    newChar = char.ToUpperInvariant(newChar);
                }
                builder.Append(newChar);
            }
            return builder.ToString();
        }
    }
}
